package com.sea.physical.controller;


import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.AjaxReturn;
import com.sea.physical.entity.CreateDistributePlan;

import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.physical.entity.CreateDistributeSku;
import com.sea.physical.service.CreateDistributePlanService;
import com.sea.physical.service.CreateDistributeSkuService;
import com.sea.physical.service.OAuth2ClientService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 分配创建发运计划
 * @author 陈鸿飞
 */
@Controller
@RequestMapping(value = "/sea/physical/distribute")
public class CreateDistributeController {
    @Autowired
    private CreateDistributePlanService createDistributePlanService;
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    @Autowired
    private CreateDistributeSkuService createDistributeSkuService;
    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        return "/sea/physical/createDistribute/main";
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     CreateDistributePlan createDistributePlan) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<CreateDistributePlan> list = createDistributePlanService.findByCnd(createDistributePlan);
        PageInfo<CreateDistributePlan> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }
    /**
     * 分页条件查询
     *
     * @param createId
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCreateId")
    public List<CreateDistributeSku> findByCreateId(Integer createId) {
        List<CreateDistributeSku> list = createDistributeSkuService.findByCreateId(createId);

        return list;
    }
    /**
     * 分配计划
     * @param id
     * @return
     */
    @RequestMapping("/createDistribute")
    @ResponseBody
    public AjaxReturn distribute(@RequestParam("id")Integer id){
        AjaxReturn result = Ajax.fail().setMsg("分配失败！");
        try {
            createDistributePlanService.distribute(id);
            result.setOk(true).setMsg("分配成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 下推计划
     * @param id
     * @return
     */
    @RequestMapping("/send")
    @ResponseBody
    public AjaxReturn send(@RequestParam("id")Integer id){
        AjaxReturn result = Ajax.fail().setMsg("下推失败！");
        try {
            createDistributePlanService.send(id);
            result.setOk(true).setMsg("下推成功！");
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }



    /**
     * 分配计划
     * @param createId
     * @return
     */
    @RequestMapping("/cancel")
    @ResponseBody
    public AjaxReturn cancel(@RequestParam("createId")Integer createId){
        AjaxReturn result = Ajax.fail().setMsg("取消失败！");
        try {
            createDistributePlanService.cancel(createId);
            result.setOk(true).setMsg("取消成功！");
//            String accessToken = "9508e61f5fef5ae3c029e3147a4b0745";
//           String accessToken = oAuth2ClientService.getToken();
//            if(StringUtils.isNotBlank(accessToken)){
//                String s = oAuth2ClientService.doForceDrawBack(accessToken, "1100795470840750109", "1143866579811254279");
//                System.out.println(s);
//                String s1 = oAuth2ClientService.deleteRequest(accessToken, "1100795470840750109", "1143866579811254279");
//                System.out.println(s1);
//
//                return result.setOk(true).setMsg("推送成功!");
//            }else {
//                return result;
//            }

        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }



    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importSku(Model model,
                                MultipartFile importSession,
                                @RequestParam("createId")Integer createId) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == importSession || importSession.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = importSession.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                InputStream is = importSession.getInputStream();
                createDistributeSkuService.importSku(is,fileName,createId);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * 导出excel
     * @param response
     * @param ids
     */
    @ResponseBody
    @RequestMapping(value = "/export")
    public void export(HttpServletResponse response, @RequestParam("ids") Integer ids[])
    {
        List<CreateDistributeSku> skuList=new ArrayList<>();
        skuList = createDistributeSkuService.getRows(ids);
        String[] title = {"PO号","供应商","SKU","箱数","渠道","shipment ID","FNSKU","产品名称","名称(英文)","颜色","尺码(CM)","尺码(INCH)","数量"
                ,"装箱量","内含件数","总件数","总毛重","总净重","总体积","采购单价","采购总价"
                ,"采购原币","币种","柜号","柜型","运输","国家","装柜地点","装柜时间","状态","单箱毛重","单箱体积","单箱长","单箱宽","单箱高","预计交期","产品毛重","产品净重","产品长","产品宽","产品高","报关名称","付款方式","船期"};
        String fileName = "分配表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "分配表";
        String[][] content = new String[skuList.size()][44];
        for (int i = 0; i < skuList.size(); i++) {
            content[i] = new String[title.length];
            CreateDistributeSku obj = skuList.get(i);
            content[i][0] = obj.getErpProducePo();
            content[i][1] = obj.getCreateSupplierName()+"";
            content[i][2] = obj.getCreateSku();
            content[i][3] = obj.getCreateBoxNumber()+"";
            content[i][4] = obj.getCreateChannelName();
            content[i][5] = obj.getCreateShipmentId();
            content[i][6] = obj.getCreateFnSku();
            content[i][7] = obj.getProductName() == null?"":obj.getProductName();
            content[i][8] = "";
            content[i][9] = obj.getProductColorName()+"";
            content[i][10] = obj.getProductCm()+"";
            content[i][11] = obj.getProductInch()+"";
            content[i][12] = obj.getCreateNumber() + "";
            content[i][13] = obj.getCreatePackage()+"";

            content[i][14] = obj.getProductContainCount()+"";
            content[i][15] = obj.getCreateNumberTotal() + "";

            content[i][16] = obj.getCreateWeightTotal()+"";
            content[i][17] = obj.getCreateKgTotal() + "";
            content[i][18] = obj.getCreateVolumeTotal().toString();

            content[i][19] = (null==obj.getErpProducePrice()?(0+""):obj.getErpProducePrice().toString());
            content[i][20] = Double.parseDouble(content[i][19])*Double.parseDouble(content[i][12])+"";
            content[i][21] = (null==obj.getProducePrice()?(0+""):obj.getProducePrice().toString());

            content[i][22] = obj.getProduceMoneyType();
            content[i][23] = obj.getCreatePlanNo();
            content[i][24] = obj.getCreatePlanCabinetName();
            content[i][25] = obj.getTransportName();
            content[i][26] = obj.getCountryName();
            content[i][27] = obj.getCreatePlanPlace();
            content[i][28] = obj.getCreatePlanPlaceDate();
            content[i][29] = obj.getCreatePlanStatus();
            content[i][30] = obj.getCreateWeight()+"";
            content[i][31] = obj.getCreateVolume()+"";
            content[i][32] = obj.getCreateBoxLength()+"";
            content[i][33] = obj.getCreateBoxWeight()+"";
            content[i][34] = obj.getCreateBoxHeight()+"";
            content[i][35] = obj.getOrderDate()+"";
            content[i][36] = obj.getProductGrossWeight()+"";
            content[i][37] = obj.getProductWeight()+"";
            content[i][38] = obj.getProductLength()+"";
            content[i][39] = obj.getProductWidth()+"";
            content[i][40] = obj.getProductHeight()+"";
            content[i][41] = obj.getProductDeclarationName()+"";
            content[i][42] = obj.getPaymentType()+"";
            content[i][43] = obj.getCreatePlanBoatDate()+"";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
